package dao;

import entity.Community;
import entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class CommunityDao {
    //增
    public int add(Community community, Connection connection) throws SQLException {
        String sql = "insert into community(community_name,community_price,community_stock,sort_id) values (?,?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, community.getCommunityName());
        statement.setDouble(2, community.getCommunityPrice());
        statement.setDouble(3,community.getCommunityStock());
        statement.setInt(4,community.getSortId());
        int count = statement.executeUpdate();
        statement.close();
        return count;
    }




    //删
    public int delete(int communityId, Connection connection) throws SQLException {
        String sql = "delete from community where community_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,communityId);

        int count = statement.executeUpdate();


        statement.close();
        return count;

    }





    //改
        public int update(Community community, Connection connection) throws SQLException {
            String sql = "update community set community_name = ?,community_price = ?,community_stock = ?,sort_id = ? where community_id = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, community.getCommunityName());
            statement.setDouble(2, community.getCommunityPrice());
            statement.setDouble(3,community.getCommunityStock());
            statement.setInt(4,community.getSortId());
            statement.setInt(5,community.getCommunityId());
            int count = statement.executeUpdate();
            statement.close();
            return count;
        }
    //查
    public Community selectById(int communityId, Connection connection) throws SQLException {
        String sql = "select * from community where community_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, communityId);
        ResultSet resultSet = statement.executeQuery();
        Community community = null;
        while (resultSet.next()){
            String communityName = resultSet.getString("community_name");
            Double communityPrice = resultSet.getDouble("community_price");
            Double communityStock = resultSet.getDouble("community_stock");
            int sortId = resultSet.getInt("sort_id");
            community = new Community(communityId,communityName,communityPrice,communityStock,sortId);
            break;
        }



        resultSet.close();
        statement.close();
        return community;
    }
}
